<!-- APS排程 -->
<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :span-method="spanMethod"
      :row-class-name="tableRowClassName"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @current-row-change="handleCurrentRowChange"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <!-- 产线分配数量 -->
      <template slot-scope="{ row }" slot="cxfpsl">
        <el-input-number
          size="mini"
          style="width: 105px"
          v-model="row.cxfpsl"
          controls-position="right"
          @change="handleChange"
          :min="0"
          placeholder="产线分配数量"
        ></el-input-number>
      </template>
      <!-- 备产时长M -->
      <template slot-scope="{ row }" slot="bcscm">
        <el-input-number
          size="mini"
          style="width: 105px"
          v-model="row.bcscm"
          controls-position="right"
          @change="handleChange"
          :min="0"
          placeholder="备产时长M"
        ></el-input-number>
      </template>
      <!-- 满足工单流转数量 -->
      <template slot-scope="{ row }" slot="mzgdlzsl">
        <el-input-number
          size="mini"
          style="width: 105px"
          v-model="row.mzgdlzsl"
          controls-position="right"
          @change="handleChange"
          :min="0"
          placeholder="满足工单流转数量"
        ></el-input-number>
      </template>
      <!-- 流转时长M -->
      <template slot-scope="{ row }" slot="lzscm">
        <el-input-number
          size="mini"
          style="width: 105px"
          v-model="row.lzscm"
          controls-position="right"
          @change="handleChange"
          :min="0"
          placeholder="流转时长M"
        ></el-input-number>
      </template>
      <!-- 排程工单状态 -->
      <template slot-scope="{ row }" slot="status">
        <span v-if="row.status === 1" style="color: #e6a23c">{{ workOrderStatus[0] }}</span>
        <span v-if="row.status === 2" style="color: #409eff">{{ workOrderStatus[1] }}</span>
      </template>
      <!-- 开始排程 -->
      <template slot="menuLeft">
        <el-button size="small" icon="el-icon-s-promotion" v-if="permission.planEnact_startSchedule" @click="handleMenu({ type: 'startSchedule' })">开始排程</el-button>
      </template>
      <!-- 修改排程 -->
      <template slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-edit"
          :disabled="scheduleIssuedDisabled"
          v-if="permission.planEnact_editSchedule"
          @click="handleMenu({ type: 'editSchedule' })"
          >修改排程</el-button
        >
      </template>
      <!-- 排程下发 -->
      <template slot="menuLeft">
        <el-button
          type="success"
          size="small"
          icon="el-icon-check"
          :disabled="scheduleIssuedDisabled"
          v-if="permission.planEnact_scheduleIssued"
          @click="handleMenu({ type: 'scheduleIssued' })"
          >排程下发
        </el-button>
      </template>
    </avue-crud>
    <!-- 开始排程 修改排程-->
    <base-modal-template
      ref="baseModal"
      :key="timer"
      :visibile.sync="baseVisibile"
      :modalStatus="modalStatus"
      :title="baseModalTitle"
      :newTableData="newTableData"
      @startPlanEnact="startPlanEnact"
      @getSelectedRows="getSelectedRows"
      @refresh="onLoad"
      @newKey="newKey"
    >
    </base-modal-template>
  </basic-container>
</template>

<script>
import { getList, planRelease } from '@/api/aps/planEnact';
import { getDictionary } from '@/api/system/dictbiz.js';
import globalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import baseModalTemplate from './components/baseModalTemplate.vue';
import { mapGetters, mapState } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
const compareTime = (time1, time2) => {
  let oDate1 = new Date(time1);
  let oDate2 = new Date(time2);
  if (oDate1.getTime() > oDate2.getTime()) {
    return 1;
  } else {
    return 2;
  }
};
export default {
  components: {
    baseModalTemplate,
    globalModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'PLAN_ENACT',
      modalStatus: 'add',
      scheduleIssuedDisabled: true,
      planId: null,
      newTableData: [],
      lineStatus: [], // 产线状态
      config: {
        title: '开始排程'
      },
      clickRowId: null,
      form: {},
      query: {},
      defaults: {},
      loading: true,
      data: [],
      commonDialog: {
        dispatch: true
      },
      baseVisibile: false, // 排程弹窗
      modalName: '', //打开公用模态框名称
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      page: {
        pageSize: 100000,
        currentPage: 1,
        total: 0
      },
      baseModalTitle: '',
      //  待下发：1， 已下发：2
      workOrderStatus: ['待下发', '已下发'],
      option: {
        height: 'calc(100vh - 240px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        selection: false,
        dialogClickModal: false,
        menu: false,
        labelWidth: 120,
        highlightCurrentRow: true,
        columnBtn: false,
        column: [
          {
            label: '车间',
            prop: 'workshopName',
            searchType: 'input',
            type: 'search'
          },
          {
            label: '产线',
            prop: 'lineName',
            width: 120
          },
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            width: 150
          },
          {
            label: '订单数量',
            prop: 'planQuantity'
          },
          {
            label: '交期',
            prop: 'deliveryDate',
            width: 140
          },
          {
            label: '运算开始时间',
            prop: 'planStartDate',
            width: 140
          },
          {
            label: '运算结束时间',
            prop: 'planEndDate',
            width: 140
          },
          {
            label: '生产工单',
            prop: 'workOrderNo'
          },
          {
            label: '工艺流程',
            prop: 'processId'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            disabled: true
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: 'TPC(M)',
            prop: 'lineTpc'
          },
          {
            label: '工单理论生产周期M',
            prop: 'workorderQuantityTpt',
            width: 130
          },
          {
            label: '分配产线数',
            prop: 'lineQuantity',
            width: 100
          },
          {
            label: '产线分配数量',
            prop: 'lineQuantity',
            width: 130,
            slot: true
          },
          {
            label: '产线理论生产周期M',
            prop: 'lineQuantityTpt',
            width: 130
          },
          {
            label: '产线状态',
            prop: 'lineState',
            type: 'select',
            html: true,
            formatter: (val) => {
              switch (val.lineState) {
                case 1:
                  return `<span class="stateWords-danger">停线</span>`;
                case 2:
                  return `<span class="stateWords-success">生产</span>`;
                default:
                  break;
              }
            },
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=line_status'
          },
          {
            label: '前工单-预计完成时间',
            prop: 'preWoPlanCompDate',
            width: 150
          },
          {
            label: '前工单-实际完成时间 ',
            prop: 'preWoActualCompDate',
            width: 150
          },
          {
            label: '备产时长M',
            prop: 'timeReadyToProduce',
            width: 130,
            slot: true
          },
          {
            label: '生产日历-生产开始时间',
            prop: 'calendarStartDate',
            width: 150
          },
          {
            label: '生产日历-生产完成时间 ',
            prop: 'calendarEndDate',
            width: 150
          },
          {
            label: '与前工单结束时间对比差异H',
            prop: 'diffPreWorkorder',
            width: 180
          },
          {
            label: '满足工单流转数量',
            prop: 'quantityForNextWo',
            slot: true,
            width: 130
          },
          {
            label: '满足流转数量所需时长M',
            prop: 'timeTurnaround',
            width: 160
          },
          {
            label: '流转时长M',
            prop: 'timeForNextWo',
            width: 130,
            slot: true
          },
          {
            label: '工单状态',
            prop: 'status',
            span: 24,
            slot: true
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ...mapState({
      realName: (state) => state.user.userInfo.real_name,
      userId: (state) => state.user.userInfo.user_id
    }),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.workorder_add, false),
        // viewBtn: this.vaildData(this.permission.workorder_view, false),
        // delBtn: this.vaildData(this.permission.workorder_delete, false),
        // editBtn: this.vaildData(this.permission.workorder_edit, false)
      };
    }
  },
  mounted() {
    // 获取产线状态
    this.getLineStatus();
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    handleCurrentRowChange(val) {
      if (val && val.productionPlanId && val.productionOrderNo) {
        this.planId = val.productionPlanId;
        this.productionOrderNo = val.productionOrderNo;
        this.scheduleIssuedDisabled = false;
      } else {
        this.scheduleIssuedDisabled = true;
      }
    },
    startPlanEnact(value) {
      let data = this._cloneDeep(value);
      this.data = [];
      // 重组数据
      data.map((d) => {
        if (d.lineList && d.lineList.length > 0) {
          this.data = this.data.concat(d.lineList);
        } else {
          this.data = this.data.concat(d);
        }
      });
      this.data = this.mergeTableRow(this.data, ['workshopName']);
      this.data.map((d) => {
        if (d.detailVO && Object.keys(d.detailVO).length > 0) {
          for (const key in d.detailVO) {
            if (key == 'planSimpleVO') {
              for (const pKey in d.detailVO.planSimpleVO) {
                d[pKey] = d.detailVO.planSimpleVO[pKey];
              }
            } else {
              d[key] = d.detailVO[key];
            }
          }
        }
        return d;
      });
      this.newTableData = this.data;
    },
    getLineStatus() {
      getDictionary({ code: 'line_status' }).then((res) => {
        if (res && res.status == 200) {
          this.lineStatus = res.data.data.map((d) => {
            return {
              label: d.dictValue,
              value: d.dictKey
            };
          });
        }
      });
    },
    tableRowClassName({ row, rowIndex }) {
      // 若【运算结束时间】在【交期】内，填充为绿色反之红色
      if (row.planEndDate && row.deliveryDate) {
        let colorStatus = compareTime(row.planEndDate, row.deliveryDate);
        if (colorStatus === 1) {
          return row['workshopName-span'].colspan == 1 ? 'warning-row main-row' : 'warning-row';
        } else if (colorStatus === 2) {
          return row['workshopName-span'].colspan == 1 ? 'success-row main-row' : 'success-row';
        }
      } else {
        return '';
      }
    },
    spanMethod({ row, column, rowIndex, columnIndex }) {
      const span = column['property'] + '-span';
      if (row[span]) {
        return row[span];
      }
    },
    // 开始排程 修改排程 排程下发
    handleMenu(params) {
      let { type } = params;
      let name = '';
      switch (type) {
        case 'startSchedule':
          this.baseModalTitle = '开始排程';
          this.baseVisibile = true;
          this.modalStatus = 'add';
          return;
        case 'editSchedule':
          this.baseModalTitle = '修改排程';
          if (!this.planId) {
            this.$message.warning('请先单击选中一条记录');
            return;
          }
          this.modalStatus = 'edit';
          this.$refs.baseModal.menuLeftForm.productionOrderNo = this.productionOrderNo;
          this.$refs.baseModal.onLoad(this.productionOrderNo);
          this.baseVisibile = true;
          return;
        case 'scheduleIssued':
          name = '排程下发';
          if (!this.planId) {
            this.$message.warning('请先单击选中一条记录');
            return;
          }
          this.$confirm(`此操作将进行${name}, 是否确定?`, `${name}`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.scheduleIssued();
          });
          break;
        default:
          break;
      }
    },
    // 排程下发
    scheduleIssued() {
      planRelease({
        planId: this.planId
      })
        .then(() => {
          this.$message.success('排程下发成功');
          this.scheduleIssuedDisabled = true;
          this.onLoad();
        })
        .catch((err) => {});
    },
    refreshChange() {
      this.onLoad();
    },
    onLoad() {
      this.loading = true;
      getList().then((res) => {
        if (res && res.data.data) {
          const data = res.data.data;
          this.data = [];
          this.page.total = 0;
          // 重组数据
          data.map((d) => {
            if (d.lineList && d.lineList.length > 0) {
              this.data = this.data.concat(d.lineList);
            } else {
              this.data = this.data.concat(d);
            }
          });
          this.data = this.mergeTableRow(this.data, ['workshopName']);
          this.data.map((d) => {
            if (d.detailVO && Object.keys(d.detailVO).length > 0) {
              for (const key in d.detailVO) {
                if (key == 'planSimpleVO') {
                  for (const pKey in d.detailVO.planSimpleVO) {
                    d[pKey] = d.detailVO.planSimpleVO[pKey];
                  }
                } else {
                  d[key] = d.detailVO[key];
                }
              }
            }
            return d;
          });
          this.loading = false;
        }
      });
    },
    // 根据条件合并行
    mergeTableRow(data, merge) {
      if (!merge || merge.length === 0) {
        return data;
      }
      merge.forEach((m) => {
        const mList = {};
        data = data.map((v, index) => {
          const rowVal = v[m];
          if (mList[rowVal] && mList[rowVal].newIndex === index) {
            mList[rowVal]['num']++;
            mList[rowVal]['newIndex']++;
            data[mList[rowVal]['index']][m + '-span'].rowspan++;
            v[m + '-span'] = {
              rowspan: 0,
              colspan: 0
            };
          } else {
            mList[rowVal] = { num: 1, index: index, newIndex: index + 1 };
            v[m + '-span'] = {
              rowspan: 1,
              colspan: 1
            };
          }
          return v;
        });
      });
      return data;
    },

    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      let findIndex = this.data.findIndex((d) => d.id == this.clickRowId);
      switch (this.modalName) {
        case 'productionOrderNoModal':
          this.data[findIndex]['productionOrderNo'] = this._get(rowData, 'orderNo', '');
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__row.warning-row {
  background-color: #f56c6c !important;
  // color: #fff;
}
::v-deep .el-table__row.success-row {
  background-color: #67c23a !important;
  // color: #fff;
}
::v-deep .el-table__row.primary-row {
  background-color: #66b1ff !important;
  // color: #fff;
}
::v-deep .el-table__row.main-row {
  td:first-child {
    background: #fff;
    color: #000;
  }
}
</style>
